<template>
<div v-show="show">
  <my-tree2 :tree="tree" :back="onBack" :refresh="onRefresh"></my-tree2>
</div>
</template>

<script>
import store from 'share/server/vuex/store.js'
import _ from 'lodash'
import async from 'async'
import ebus from 'libs/ebus.js'
import {getQueryStringArgs} from 'libs/utils.js'
import {mediaApi, streamSrcApi} from 'share/server/api.js'
import {encryptPassword} from 'share/server/utils.js'
import {getPlatformInfo, tryLogin, doLogout} from 'share/server/vuex/actions/system.js'
import {doLoadMtSrcs} from 'share/server/vuex/actions/streamsrc.js'
import {doLoadMonitors} from 'share/server/vuex/actions/media.js'

import { Indicator } from 'mint-ui'
import { MessageBox } from 'mint-ui'

export default {
  store,
  vuex: {
    getters: {
      monitor: (state) => state.monitor,
      mtsrcs: (state) => state.mtsrc.list
    },
    actions: {
      getPlatformInfo,
      tryLogin,
      doLogout,
      doLoadMtSrcs,
      doLoadMonitors
    }
  },
  data () {
    return {
      show: false,
      tree: {
        name: this.$t('app.monitorPlatform'),
        childs: [],
        curr: null,
        root: null
      }       
    }
  },
  methods: {
    onBack () {
      var curr = this.tree.curr
      this.tree.root.curr = curr.father
    },
    onRefresh () {
      if (this.tree.root === this.tree.curr) {
        this.doLoadMonitors()
      } else {
        this.getDevsOfTree(this.tree.curr, true)
      }
    },
    encryptPassword (plaintext) {
      //兼容旧版本，待废弃
      if (plaintext === 'admin') {
        return plaintext
      } else {
        return encryptPassword(plaintext)
      }   
    },
    stepGetPlatformInfo (cb) {
      let ctx = this
      this.getPlatformInfo({
        success () {
          cb(null)
        },
        error (data) {
          cb('get platform info error')
        },
        noResponse () {
          cb('get platform info  noResponse')
        }
      })
    },
    stepLogin (cb) {
      let router = this.$router
      if (!this.verify) {
        this.verify = {
          username: 'admin',
          password: 'admin'
        }
      }
      let ctx = this
      let req = {
        username: this.verify.username,
        password: this.encryptPassword(this.verify.password),
        code: ''
      }

      this.tryLogin(req, {
        success () {
          cb(null)
        },
        error (data) {
          cb('login error')
        },
        noResponse () {
          cb('login noResponse')
        }
      })      
    },
    stepLoadMonitorInfo (cb) {
      this.doLoadMtSrcs()
      this.doLoadMonitors()
      cb(null)
    },    
    onConnect () {
      async.waterfall([
        this.stepGetPlatformInfo,
        this.stepLogin,
        this.stepLoadMonitorInfo,
        ], 
        function (err) {
          if (err) {
            console.log(err)
            setTimeout(this.onConnect, 3000)
          } else {
            this.show = true
            Indicator.close()
          }
        }.bind(this)
      )
    },
    doConnect () {
      Indicator.open()
      this.onConnect()
    },
    onLoseConnection () {
      if (this.show) {
        this.doLogout()
        location.reload(true)
      }
    },
    isFolderDev (devType) {
      return _.includes(['nvr', 'dvr'], devType)
    },
    mtsrcConnect (tree) {
      var device = tree.data
      var rootMonitor = device.rootMonitor
      var mtsrc = {
        name: device.name,
        tag: '',
        monitorOfId: rootMonitor._id,
        deviceOfName: device.name,
        topoIdOfMediaDev: rootMonitor.topoIdOfMediaDev,
        srcDeviceId: device.deviceId
      }

      tree.loading = true
      streamSrcApi.setItem('mtsrcs', mtsrc).then(function(res) {
        if (res && res.data && res.data.code === 0) {
          this.doLoadMtSrcs()
          this.initMtsrcActionWithDisconnect(tree.actions.mtsrc)
          this.sortTree(tree.father)
        }
        tree.loading = false
      }.bind(this), function(res) {})
    },
    mtsrcDisconnect (tree) {
      var device = tree.data
      var rootMonitor = device.rootMonitor
      var mtsrc = this.getMtsrcWithDeviceId(rootMonitor._id, device.deviceId)
      if (!mtsrc) {
        return
      }

      tree.loading = true
      streamSrcApi.delItem('mtsrcs', mtsrc._id).then(function(res) {
        if (res && res.data && res.data.code === 0) {
          this.doLoadMtSrcs()
          this.initMtsrcActionWithConnect(tree.actions.mtsrc)
          this.sortTree(tree.father)
        }
        tree.loading = false
      }.bind(this), function(res) {})
    },
    initMtsrcActionWithConnect (action) {
      action.name = this.$t('common.connect')
      action.doClick = this.mtsrcConnect
      action.type = 'primary'
    },
    initMtsrcActionWithDisconnect (action) {
      action.name = this.$t('common.disconnect')
      action.doClick = this.mtsrcDisconnect
      action.type = 'danger'
    },
    initFolderAction (action) {
      action.name = this.$t('common.open')
      action.doClick = this.doOpenFolder
      action.type = 'primary'
    },
    getMtsrcWithDeviceId (monitorId, deviceId) {
      let mtsrc = _.find(this.mtsrcs, (item) => {
        if (item.monitorOfId != monitorId
          || item.srcDeviceId != deviceId) {
          return false
        } else {
          return true
        }
      })

      return mtsrc
    },
    addChild (tree, device) {
      var action = {}
      let rootMonitor = device.rootMonitor
      var child = {
        name: device.name,
        devType: device.devType,
        childs: [],
        isFolder: this.isFolderDev(device.devType),
        loading: false,
        data: device,
        root: tree.root,
        father: tree,
        actions: {}
      } 
      if (child.isFolder) {
        child.icon = 'octicon octicon-server'
        this.initFolderAction(action)
        child.actions.open = action
      } else {
        child.icon = 'octicon octicon-device-camera-video'
        let mtsrc = this.getMtsrcWithDeviceId(rootMonitor._id, device.deviceId)
        if (mtsrc) {
          this.initMtsrcActionWithDisconnect(action)
        } else {
          this.initMtsrcActionWithConnect(action)
        }
        child.actions.mtsrc = action
      }

      tree.childs.splice(tree.childs.length, 0, child)
    },
    sortTree (tree) {
      let childs = _.orderBy(tree.childs, ['isFolder', 'actions.mtsrc.name', 'name'], ['desc', 'asc', 'asc'])
      tree.childs = childs
    },
    getDevsOfTree (tree, force) {
      if ((!force)
        && (tree.childs.length > 0)) {
        tree.root.curr = tree
        return
      }

      let rootMonitor = null
      let device = tree.data
      if (tree.devType === 'monitor') {
        rootMonitor = device
      } else {
        rootMonitor = device.rootMonitor
      }

      tree.childs.splice(0, tree.childs.length)

      var req = {
        topoIdOfMediaDev: rootMonitor.topoIdOfMediaDev,
        monitorName: rootMonitor.name
      }
      if (rootMonitor != device) {
        req.deviceId = device.deviceId
        if (!_.isNil(usrCfg.nodeId)) {
          req.deviceId = usrCfg.nodeId
        }
      }

      tree.loading = true
      mediaApi.sendCmd('getDevicesOfMonitor', req).then(function(res) {
        if (res && res.data && res.data.code === 0) {
          var devices = res.data.data.devicesOfMonitor
          _.forEach(devices, function(item) {
            item.rootMonitor = rootMonitor
            this.addChild(tree, item)
          }.bind(this))
          tree.root.curr = tree
          this.sortTree(tree)
        } else {
          MessageBox.alert(this.$t('error.code', {code: res.data.code}), this.$t('common.fail'))
        }
        tree.loading = false
      }.bind(this), function(res) {})
    },
    doOpenFolder (tree) {
      this.getDevsOfTree(tree, false)
    },
    onLoadMonitors () {
      this.tree.childs.splice(0, this.tree.childs.length)
      _.forEach(this.monitor.list, function(item) {
        var action = {}
        var child = {
          name: item.name,
          devType: 'monitor',
          childs: [],
          isFolder: true,
          loading: false,
          icon: 'octicon octicon-server',
          data: item,
          root: this.tree,
          father: this.tree,
          actions: {}          
        }
        this.initFolderAction(action)
        child.actions.open = action
        this.tree.childs.splice(this.tree.childs.length, 0, child)
      }.bind(this))      
    }
  },
  ready () {
    ebus.on('set-monitors', this.onLoadMonitors)
    ebus.on('lose-connection', this.onLoseConnection)
    let args = getQueryStringArgs()
    if (args && args['username'] && args['password']) {
      this.verify = {
        username: args['username'],
        password: args['password']
      }
    }
    this.doConnect()    
  },
  created () {
    this.tree.curr = this.tree
    this.tree.root = this.tree
  }
}
</script>

<style>
html,body {
  margin: 0;
  padding: 0;
}
body,button, input, select, textarea,h1 ,h2, h3, h4, h5, h6 { 
  font-family: Microsoft YaHei, '宋体', Tahoma, Helvetica, Arial, "\5b8b\4f53", sans-serif;
}
</style>